﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Text;

namespace SP.OpenSource.CDC.Monitor.BLL
{
    class Scheduler
    {
        String m_sExePath = String.Empty;
        String m_sErrorMessage = String.Empty;

        System.Diagnostics.EventLog appLog = null ; 

        public Scheduler()
        {
            m_sExePath = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
            appLog = new System.Diagnostics.EventLog();
        }

        public bool MonitorCDC(String sCmdArgs)
        {
            try
            {
                
                DataSet dsConfigurations = new DataSet();
                if (false == System.IO.File.Exists(m_sExePath + "\\Config\\Configuration.dat"))
                {//raise an error to event handler
                    appLog.Source = "MonitorCDC";
                    appLog.WriteEntry("Exception raised. Cannot find configuration file. Make sure MonitorCDC application is installed.");
                    return false;
                }

                //Clean data table to avoid duplication.
                if (null != dsConfigurations && dsConfigurations.Tables.Count > 0 && dsConfigurations.Tables[0].Rows.Count > 0)
                    dsConfigurations.Tables.RemoveAt(0);
                
                dsConfigurations.ReadXml(m_sExePath + "\\Config\\Configuration.dat", XmlReadMode.ReadSchema);
                
                if (null == dsConfigurations || dsConfigurations.Tables[0].Rows.Count <= 1)
                    return true; //nothing to monitor

                String sSelectStatement = String.Empty;
                if (sCmdArgs.ToUpper() == "ALL")
                {
                    sSelectStatement = "ConfigurationID >= 0";
                }
                else
                {
                    String sQuotedConn = String.Empty;
                    if(false == BLL.Utils.GetQuotedString(sCmdArgs, ref sQuotedConn))
                    {
                        //Event log
                        appLog.Source = "MonitorCDC";
                        appLog.WriteEntry("Exception raised, while parsing command argument. Module: Scheduler.");
                        return false;
                    }

                    sSelectStatement = "ConfigurationName in (" + sQuotedConn + ")";
                }
                DataRow[] drSelected = dsConfigurations.Tables[0].Select(sSelectStatement);

                foreach (DataRow drT in drSelected)
                {
                    String sCDCStatus = String.Empty;
                    String sServerName = String.Empty;
                    String sDBName = String.Empty;
                    String sProvider = String.Empty;
                    String sIntegrartedSecurity = String.Empty;
                    String sUsername = String.Empty;
                    String sPasword = String.Empty;
                    String sSMTPPassword = String.Empty;
                    bool bCheckErrorLog = false;
                    
                    String sCDCDBConnection = drT["CDCStateConnectionString"].ToString();
                    String sEncryptionType = drT["PasswordEncryptionType"].ToString();
                    String sSMTPServer = drT["SMTPServer"].ToString();
                    String sAuthRequired = drT["SMTPAuthRequired"].ToString();
                    String sSMTPUsername = drT["SMTPUsername"].ToString();
                    String sSMTPEnPassword = drT["SMTPPassword"].ToString();
                    String sUseSSL = drT["UseSSL"].ToString();
                    String sUserDefaultPort = drT["UseDefaultPort"].ToString();
                    String sCustomPort = drT["CustomPort"].ToString();
                    String sEmailFrom = drT["EmailFrom"].ToString();
                    String sEmailTo = drT["EmailTo"].ToString();
                    String sUseDefaultSubject = drT["UseDefaultSubject"].ToString();
                    String sSubject = drT["Subject"].ToString();
                    String sMessageTemplate = drT["MessageTemplateName"].ToString();

                    if (sSMTPServer.Length > 0)
                    {
                        m_sErrorMessage = String.Empty;
                        BLL.Utils.ParseConnectionString(sCDCDBConnection, ref sServerName, ref sDBName,
                                           ref sProvider, ref sIntegrartedSecurity, ref sUsername, ref sPasword,
                                             ref m_sErrorMessage);

                        if (sIntegrartedSecurity != "True")
                        {
                            String sEncryPassword = drT["EncryptedConnectionPassword"].ToString();
                            m_sErrorMessage = String.Empty;
                            if (false == BLL.Crypt.Decrypt(sEncryPassword, sEncryptionType, ref sPasword, ref m_sErrorMessage))
                            {
                                //Event log
                                appLog.Source = "MonitorCDC";
                                appLog.WriteEntry("Module: Scheduler. Exception raised, while decrypting SMTP password. Message: " + m_sErrorMessage);

                                return false;
                            }
                            sCDCDBConnection = BLL.Utils.BuildConnectionString(sServerName,sDBName,false,sUsername,sPasword,sProvider,ref m_sErrorMessage);
                        }
                    
                        BLL.CDCManagement m_oCDCManagement = new BLL.CDCManagement();
                        BLL.EmailHelper oEmailHelper = new BLL.EmailHelper();
                        DataTable dtErrorLog = new DataTable("CDCErrorLog");

                        if (false == BLL.Crypt.Decrypt(sSMTPEnPassword, sEncryptionType, ref sSMTPPassword, ref m_sErrorMessage))
                        {//Event log
                            appLog.Source = "MonitorCDC";
                            appLog.WriteEntry("Module: Scheduler. Exception raised, while decrypting SMTP password. Message: " + m_sErrorMessage);

                            return false;
                        }

                        if (true == m_oCDCManagement.IsCDCEnabledDB(sCDCDBConnection, sDBName, ref m_sErrorMessage))
                        {
                            sCDCStatus = "Enabled";
                            bCheckErrorLog = true;
                        }
                        else
                        {
                            sCDCStatus = "Disabled";
                            String sMessageBody = oEmailHelper.PrepareMsg(m_sExePath + "/EmailTemplates/", sMessageTemplate + ".htm",
                                                                          sServerName, sCDCStatus, ref dtErrorLog);

                            //Send an alert, with blank ErrorLog
                            if (false == oEmailHelper.SendMailMessage(sSMTPServer, (sAuthRequired == "Yes" ? true : false), sSMTPUsername, sSMTPPassword,
                                     (sUserDefaultPort == "Yes" ? true : false), (sUseSSL == "Yes" ? true : false),
                                     sCustomPort, sEmailFrom, sEmailTo, sSubject, sMessageBody, ref m_sErrorMessage))
                            {//Event handler
                                appLog.Source = "MonitorCDC";
                                appLog.WriteEntry("Module: Scheduler. Exception raised, while sending email. Message: " + m_sErrorMessage);

                                return false;
                            }
                            bCheckErrorLog = false;
                        }

                        if (bCheckErrorLog == true)
                        {
                            
                            m_sErrorMessage = String.Empty;
                            BLL.Monitor.GetErrorLog(sCDCDBConnection, ref dtErrorLog, ref m_sErrorMessage);

                            if (null != dtErrorLog && dtErrorLog.Rows.Count > 0)
                            {
                                String sMessageBody = oEmailHelper.PrepareMsg(m_sExePath + "/EmailTemplates/", sMessageTemplate + ".htm", sServerName, sCDCStatus,
                                                  ref dtErrorLog);

                                if (sUseDefaultSubject == "Yes")
                                    sSubject = "CDC on " + sServerName + " needs immediate attention!";

                                m_sErrorMessage = String.Empty;
                                if (false == oEmailHelper.SendMailMessage(sSMTPServer, (sAuthRequired == "Yes" ? true : false), sSMTPUsername, sSMTPPassword,
                                             (sUserDefaultPort == "Yes" ? true : false), (sUseSSL == "Yes" ? true : false),
                                             sCustomPort, sEmailFrom, sEmailTo, sSubject, sMessageBody, ref m_sErrorMessage))
                                {//Event handler
                                    appLog.Source = "MonitorCDC";
                                    appLog.WriteEntry("Module: Scheduler. Exception raised, while sending email. Message: " + m_sErrorMessage);

                                    return false;
                                }

                            }
                        }
                    }
                }
                
                return true;
            }
            catch (Exception ex)
            {
                appLog.Source = "MonitorCDC";
                appLog.WriteEntry("Module: Scheduler. Exception raised, while parsing command argument. Message: " + ex.Message);
                return false;
            }
        }
    }
}
